/**
 * 通用js方法封装处理
 * Copyright (c) 2019 ruoyi
 */

import { v4 as uuidv4 } from 'uuid';
import { createOss } from '@/utils/alioss.js';
import { useAppEnvStoreRef } from "@/utils/appEnv";
import useUserStore from '@/store/modules/user';

const { appEnv } = useAppEnvStoreRef()

// 判断是不是学生
export function isStudent() {
  let res = useUserStore().roles.some(e => e.name == "学生组")
  return res

}


// 判断是不是老师
export function isTeach() {
  let res = useUserStore().roles.some(e => e.name == "老师组")
  return res

}

// 判断是不是管理员
export function isAdmin() {
  let res = useUserStore().roles.some(e => e.name == "管理组")
  return res

}



const ossurlCpt = computed(() => {
  let ossurl = 'banke'
  if (import.meta.env.MODE === 'production') ossurl = `pro_${ossurl}`
  else ossurl = `dev_${ossurl}`
  if (unref(appEnv).key && unref(appEnv).key !== 'xsj') ossurl = `${ossurl}_${unref(appEnv).key}`
  return ossurl
})

const VITE_UPLOAD_URL = import.meta.env.VITE_UPLOAD_URL

//时间间隔函数
export function timeInterval(timesData) {
  //如果时间格式是正确的，那下面这一步转化时间格式就可以不用了
  var dateBegin = timesData;//将-转化为/，使用new Date
  var dateEnd = new Date();//获取当前时间
  var dateDiff = Math.abs(dateEnd.getTime() - dateBegin);  //时间差的毫秒数
  var yearDiff = Math.floor(dateDiff / (24 * 3600 * 1000 * 365));
  var dayDiff = Math.floor(dateDiff / (24 * 3600 * 1000));  //计算出相差天数
  var leave1 = dateDiff % (24 * 3600 * 1000)    //计算天数后剩余的毫秒数
  var hours = Math.floor(leave1 / (3600 * 1000))//计算出小时数
  //计算相差分钟数
  var leave2 = leave1 % (3600 * 1000)    //计算小时数后剩余的毫秒数
  var minutes = Math.floor(leave2 / (60 * 1000))//计算相差分钟数
  //计算相差秒数
  var leave3 = leave2 % (60 * 1000)      //计算分钟数后剩余的毫秒数
  var seconds = Math.round(leave3 / 1000);
  var timesString = '';
  if (yearDiff != 0) {
    timesString = yearDiff + '年前';
  } else if (yearDiff == 0 && dayDiff != 0) {
    timesString = dayDiff + '天前';
  } else if (dayDiff == 0 && hours != 0) {
    timesString = hours + '小时前';
  } else if (hours == 0 && minutes != 0) {
    timesString = minutes + '分钟前';
  } else if (minutes == 0 && seconds < 60) {
    timesString = '刚刚';
  }
  return timesString
}

// 时间戳转yyyy-MM-dd HH:mm:ss
export function _formatTimestamp(timestamp) {
  const date = new Date(timestamp);

  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

export function m3u8Status(status) {
  switch (status) {
    case 0:
      return '未处理' // 未处理 m3u8转换未开始（还是处在初始文件为mp4的状态）
    case 1:
      return '处理中' // m3u8转换中
    case 2:
      return '转换成功' // m3u8转换成功
    case 3:
      return '处理失败' // m3u8转换失败
    case 4:
      return '续传成功' //代表minio续传成功
    default:
      return '未知错误'
  }
}



// 切换角色文字
export function rolesName(name) {
  if (name == "管理组") {
    return '管理员'
  } else if (name == "老师组") {
    return '老师'
  } else if (name == "学生组") {
    return '学生'
  }
}

// 切换单位
export function SwitchUnits(size) {
  let length=size/1073741824
    // 判断数值大小并转换单位
    if (length >= 1) {
      return length.toFixed(1) + 'G';
    } else {
        return (length * 1000).toFixed(0) + 'M';
    }


  
}


// 日期格式化
export function parseTime(time, pattern) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    } else if (typeof time === 'string') {
      time = time.replace(new RegExp(/-/gm), '/').replace('T', ' ').replace(new RegExp(/\.[\d]{3}/gm), '');
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

// 下载教学设计中的文件
export function downLoadDesignFile(item) {
  // 根据b取后半部分
  let pathTail = item.url.replace(cutAfterSecondSlash2(item.url), "");
  console.log(pathTail);
  window.open(VITE_MINIO_PATH + pathTail + "?filename=" + item.customName)
}


//生成年月日路径
export function getFilePath() {
  let date = new Date();
  let year = date.getFullYear() + "";
  let month = date.getMonth() + 1
  month = month < 10 ? "0" + month : month + "";
  let day = date.getDate();
  day = day < 10 ? "0" + day : day + "";
  return `xsj/${unref(ossurlCpt)}/${year}/${month}/${day}/`
}


//生成minio上传路径
export function getMinIOFilePath(role = "student") {
  let date = new Date();
  let year = date.getFullYear() + "";
  let month = date.getMonth() + 1
  month = month < 10 ? "0" + month : month + "";
  let day = date.getDate();
  day = day < 10 ? "0" + day : day + "";
  return `${unref(ossurlCpt)}/${role}/${year}/${month}/${day}/`
}


//根据文件类型返回不同的图标
export function getFileIcon(filename) {
  let suffix = filename.substring(filename.lastIndexOf(".") + 1);
  suffix = suffix.toLowerCase()

  if (suffix == "jpg" || suffix == "png" || suffix == "jpge" || suffix == "webp") {
    return "icon-tupian-copy"
  } else if (suffix == 'mp4') {
    return "icon-shipin"
  } else if (suffix == 'zip' || suffix == "rar") {
    return "icon-yasuobao"
  } else if (suffix == 'pdf') {
    return "icon-Pdf"
  } else if (suffix == 'docx' || suffix == 'doc' || suffix == 'rtf') {
    return "icon-Word"
  } else if (suffix == 'ppt' || suffix == 'pptx') {
    return 'icon-PPT'
  } else if (suffix == 'xls' || suffix == 'xlsx') {
    return 'icon-Excel'
  } else if (suffix == 'txt') {
    return 'icon-txt1'
  } else {
    return "icon-weizhiwenjian"
  }
}


//生成文件名及后缀
export function getFileName(filename) {
  let suffix = filename.substring(filename.lastIndexOf("."));
  suffix = suffix.toLowerCase()
  return uuidv4() + suffix
}

//获取没有横线的uuid
export function getOnlyUid() {
  let uid = uuidv4().replaceAll("-", "");
  let random = String(String(Math.random()).substring(3, 6));
  return uid + random;
}


// 获取文件后缀名

export function getFileHzm(fileName) {
  let suffix = fileName.substring(fileName.lastIndexOf("."));
  return suffix
}

//文件大小转换
export function filterSize(size) {
  if (!size) return '';
  if (size < pow1024(1)) return size + 'B';
  if (size < pow1024(2)) return (size / pow1024(1)).toFixed(1) + 'KB';
  if (size < pow1024(3)) return (size / pow1024(2)).toFixed(1) + 'M';
  if (size < pow1024(4)) return (size / pow1024(3)).toFixed(1) + 'G';
  return (size / pow1024(4)).toFixed(1) + 'T'
}

function pow1024(num) {
  return Math.pow(1024, num)
}


//截取字符串中间部分为省略号
export function giveEllipsisStr(str, len = 30) {

  if (str.length > len) {
    let first = str.substring(0, len - 10);
    let last = str.slice(-8);
    let mystr = first + "..." + last;
    return mystr;
  }
  return str;
}

//截取字符串后面是省略号
export function giveEllipsisStr1(str, len = 5) {
  if (str.length > len) {
    let first = str.substring(0, len);
    let mystr = first + "...";
    return mystr;
  }
  return str;
}


//根据状态显示不同的配色方案
export function giveTagState(str = "") {
  if (str === '已发布') {
    return "primary"
  } else if (str === '未开始') {
    return 'warning'
  } else if (str === '未发布') {
    return 'info'
  } else {
    return 'info'
  }
}

//学生提交作业的不同状态配色方案
export function getTagState(status = "") {
  if (status === '-1') {
    // return "warning"
    return "danger"
  } else if (status === '0') {
    return ''
  } else if (status === '1') {
    return 'success'
  }
}


//判断富文本是否为空
export function isEditEmpty(str) {
  if (str == '<p><br></p>') {
    return true;
  } else {
    return false;
  }
}


//富文本转纯文本
export function ToText(HTML) {
  var input = HTML;
  return input.replace(/<(style|script|iframe)[^>]*?>[\s\S]+?<\/\1\s*>/gi, '').replace(/<[^>]+?>/g, '').replace(/\s+/g, ' ').replace(/ /g, ' ').replace(/>/g, ' ');
}


// 表单重置
export function resetForm(refName) {
  if (this.$refs[refName]) {
    this.$refs[refName].resetFields();
  }
}

// 添加日期范围
export function addDateRange(params, dateRange, propName) {
  let search = params;
  search.params = typeof (search.params) === 'object' && search.params !== null && !Array.isArray(search.params) ? search.params : {};
  dateRange = Array.isArray(dateRange) ? dateRange : [];
  if (typeof (propName) === 'undefined') {
    search.params['beginTime'] = dateRange[0];
    search.params['endTime'] = dateRange[1];
  } else {
    search.params['begin' + propName] = dateRange[0];
    search.params['end' + propName] = dateRange[1];
  }
  return search;
}


// 回显数据字典
export function selectDictLabel(datas, value) {
  if (value === undefined) {
    return "";
  }
  var actions = [];
  Object.keys(datas).some((key) => {
    if (datas[key].value == ('' + value)) {
      actions.push(datas[key].label);
      return true;
    }
  })
  if (actions.length === 0) {
    actions.push(value);
  }
  return actions.join('');
}

// 回显数据字典（字符串数组）
export function selectDictLabels(datas, value, separator) {
  if (value === undefined) {
    return "";
  }
  var actions = [];
  var currentSeparator = undefined === separator ? "," : separator;
  var temp = value.split(currentSeparator);
  Object.keys(value.split(currentSeparator)).some((val) => {
    var match = false;
    Object.keys(datas).some((key) => {
      if (datas[key].value == ('' + temp[val])) {
        actions.push(datas[key].label + currentSeparator);
        match = true;
      }
    })
    if (!match) {
      actions.push(temp[val] + currentSeparator);
    }
  })
  return actions.join('').substring(0, actions.join('').length - 1);
}

// 字符串格式化(%s )
export function sprintf(str) {
  var args = arguments, flag = true, i = 1;
  str = str.replace(/%s/g, function () {
    var arg = args[i++];
    if (typeof arg === 'undefined') {
      flag = false;
      return '';
    }
    return arg;
  });
  return flag ? str : '';
}

// 转换字符串，undefined,null等转化为""
export function parseStrEmpty(str) {
  if (!str || str == "undefined" || str == "null") {
    return "";
  }
  return str;
}

// 数据合并
export function mergeRecursive(source, target) {
  for (var p in target) {
    try {
      if (target[p].constructor == Object) {
        source[p] = mergeRecursive(source[p], target[p]);
      } else {
        source[p] = target[p];
      }
    } catch (e) {
      source[p] = target[p];
    }
  }
  return source;
}

/**
 * 构造树型结构数据
 * @param {*} data 数据源
 * @param {*} id id字段 默认 'id'
 * @param {*} parentId 父节点字段 默认 'parentId'
 * @param {*} children 孩子节点字段 默认 'children'
 */
export function handleTree(data, id, parentId, children) {
  let config = {
    id: id || 'id',
    parentId: parentId || 'parentId',
    childrenList: children || 'children'
  };

  var childrenListMap = {};
  var nodeIds = {};
  var tree = [];

  for (let d of data) {
    let parentId = d[config.parentId];
    if (childrenListMap[parentId] == null) {
      childrenListMap[parentId] = [];
    }
    nodeIds[d[config.id]] = d;
    childrenListMap[parentId].push(d);
  }

  for (let d of data) {
    let parentId = d[config.parentId];
    if (nodeIds[parentId] == null) {
      tree.push(d);
    }
  }

  for (let t of tree) {
    adaptToChildrenList(t);
  }

  function adaptToChildrenList(o) {
    if (childrenListMap[o[config.id]] !== null) {
      o[config.childrenList] = childrenListMap[o[config.id]];
    }
    if (o[config.childrenList]) {
      for (let c of o[config.childrenList]) {
        adaptToChildrenList(c);
      }
    }
  }

  return tree;
}

/**
 * 参数处理
 * @param {*} params  参数
 */
export function tansParams(params) {
  let result = ''
  for (const propName of Object.keys(params)) {
    const value = params[propName];
    var part = encodeURIComponent(propName) + "=";
    if (value !== null && typeof (value) !== "undefined") {
      if (typeof value === 'object') {
        for (const key of Object.keys(value)) {
          if (value[key] !== null && typeof (value[key]) !== 'undefined') {
            let params = propName + '[' + key + ']';
            var subPart = encodeURIComponent(params) + "=";
            result += subPart + encodeURIComponent(value[key]) + "&";
          }
        }
      } else {
        result += part + encodeURIComponent(value) + "&";
      }
    }
  }
  return result
}


// 返回项目路径
export function getNormalPath(p) {
  if (p.length === 0 || !p || p == 'undefined') {
    return p
  }
  let res = p.replace('//', '/')
  if (res[res.length - 1] === '/') {
    return res.slice(0, res.length - 1)
  }
  return res;
}

// 验证是否为blob格式
export async function blobValidate(data) {
  try {
    const text = await data.text();
    JSON.parse(text);
    return false;
  } catch (error) {
    return true;
  }
}


//判断是否为空对象
export function isEmptyObj(obj) {
  if (Object.keys(obj).length === 0) {
    return false
  }
  return true
}

//文件下载
//filename:文件名  fileurl:下载地址
export async function createDomLink(downloadName, ossName) {
  const client = await createOss();
  // 配置响应头实现通过URL访问时自动下载文件，并设置下载后的文件名。
  const filename = downloadName;
  const response = {
    'content-disposition': `attachment; filename=${encodeURIComponent(
      filename,
    )}`,
  };
  // 填写Object完整路径。Object完整路径中不能包含Bucket名称。
  const url = client.signatureUrl(ossName, { response });
  // 创建一个a标签
  var tempLink = document.createElement('a');
  // 隐藏a标签
  tempLink.style.display = 'none';
  // 设置a标签的href属性为blob对象转化的URL
  tempLink.href = url;
  // 给a标签添加下载属性
  tempLink.setAttribute('download', filename);
  // if (typeof tempLink.download === 'undefined') {
  tempLink.setAttribute('target', '_blank');
  // }
  document.body.appendChild(tempLink);
  // 启动下载
  tempLink.click();
  // 下载完毕删除a标签
  document.body.removeChild(tempLink);
  window.URL.revokeObjectURL(url);
}


//文件下载
//filename:文件名  fileurl:下载地址
export function minIoCreateDomLink(filename, path) {
  return `${VITE_UPLOAD_URL}/download/${path}&filename=${filename}`
}


export function downLoadFile(item) {

  if (item == null) {
    ElMessage.error("资料丢失了，请联系任课老师！！")
    return;
  }
  let path = '';
  
  // 资料下载
  if(item.file_url ){
    const royIndex = item.file_url.indexOf('roy/');
    path =  item.file_url.substring(royIndex + 4)
    let url = minIoCreateDomLink(item.name, path);
    window.open(url);
  }else{
    path = ""
  }
  // 作业附件下载
  if(item.path){
    const royIndex = item.path.indexOf('roy/');
    path =  item.path.substring(royIndex + 4)
    let url = minIoCreateDomLink(item.original_filename, path);
    window.open(url);
  }else{
     path = ""
  }

  
    


}


/**
 * 通过url下载文件并对下载的文件更名
 * @param {*} url
 * @param {*} filename
 */
export const minIoCreateDomLink2 = (url, filename) => {
  function getBlob(url) {
    console.log(url);
    return new Promise(resolve => {
      const XML = new XMLHttpRequest();
      XML.open('GET', url, true);
      XML.responseType = 'blob';
      XML.onload = () => {
        if (XML.status === 200) {
          resolve(XML.response);
        }
      };
      XML.send();
    });
  }

  //下载文件
  function saveAs(blob, filename) {
    const elelink = document.createElement("a");
    elelink.style.display = 'none';
    elelink.download = filename;
    elelink.href = window.URL.createObjectURL(blob);
    document.body.appendChild(elelink);
    elelink.click();
    document.body.removeChild(elelink);
  }

  // 调用以上方法进行下载
  getBlob(url).then(blob => {
    saveAs(blob, filename);
  });
}






